package com.ujcms.cms.core;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 任务执行器配置
 *
 * @author PONY
 */
@Configuration
@EnableAsync
public class TaskExecutorConfig {
    /**
     * 默认任务执行器。
     * <p>
     * 因为增加了自定义的`ThreadPoolTaskExecutor`，这个默认的`ThreadPoolTaskExecutor`就不会再创建了，需要自行创建。
     */
    @Lazy
    @Primary
    @Bean(name = {TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME,
            AsyncAnnotationBeanPostProcessor.DEFAULT_TASK_EXECUTOR_BEAN_NAME})
    public ThreadPoolTaskExecutor applicationTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
        return taskExecutor;
    }

    /**
     * 生成器任务执行器。为生成功能定义专门的任务执行器，和公用的任务执行器分开，以免相互影响。
     */
    @Lazy
    @Qualifier("generator")
    @Bean
    public ThreadPoolTaskExecutor generatorTaskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(1);
        taskExecutor.setMaxPoolSize(2);
        taskExecutor.setQueueCapacity(2048);
        taskExecutor.setAllowCoreThreadTimeOut(true);
        taskExecutor.setKeepAliveSeconds(60);
        taskExecutor.setAwaitTerminationMillis(5000);
        taskExecutor.setThreadNamePrefix("task-generator-");
        return taskExecutor;
    }
}
